//
//  DBSleepData.m
//  CareRingApp
//
//  Created by Linktop on 2022/11/1.
//

#import "DBSleepData.h"
#import "TimeUtils.h"
//#import "DBValueSuper.h"
#import "DBHrv.h"
#import "DBThermemoter.h"

#import "ContributionScoreObj.h"
//#import "TrendCommonObj.h"
//#import "tools.h"
#import "DBHistoryDataSr03.h"
#import <MJExtension/MJExtension.h>
#import "Tools.h"

NSString * const TABLE_NM_SLEEP_DATA = @"table_sleep_data";


@implementation DBSleepData
{
    NSDateFormatter *_formatter;
}

+(instancetype)dbDataWithmacAddress:(NSString *)macAddress StagingData:(StagingDataV2 *)stagingData
{
    
    if (macAddress == nil || stagingData == nil) {
        return nil;
    }
    
    DBSleepData *data = [[DBSleepData alloc]init];
    data.macAddress = macAddress;
    data.stagingData = stagingData;
    return data;
}

+(instancetype)copyWithDbSleepData:(DBSleepData *)oriSleep
{
    
    DBSleepData *newSleep = [[DBSleepData alloc]init];
    
    newSleep.sleepStart = oriSleep.sleepStart ;
    newSleep.sleepEnd = oriSleep.sleepEnd ;
    newSleep.dateString = oriSleep.dateString ; //格式化时间
    newSleep.macAddress = oriSleep.macAddress ;

     // @property(strong, nonatomic) NSNumber *
    newSleep.restHR = oriSleep.restHR ; //睡眠当天的静息心率

    newSleep.hr = oriSleep.hr ; //睡眠期间的平均心率
    newSleep.hrv = oriSleep.hrv ; //睡眠期间的hrv
    newSleep.br = oriSleep.br ; // 睡眠期间的呼吸率
    newSleep.spo2 = oriSleep.spo2 ; //睡眠期间的血氧



    newSleep.hrDip = oriSleep.hrDip ; //心率沉浸比例 float
    newSleep.duration = oriSleep.duration ; //睡眠时长
    newSleep.qulalityDuration = oriSleep.qulalityDuration ; //优质睡眠时长
    newSleep.deepDuration = oriSleep.deepDuration ; //深度睡眠时长

    newSleep.effieiency = oriSleep.effieiency ; // 处理wake其他时间和 / 总时间
    newSleep.stagingData = oriSleep.stagingData ;
    
    return newSleep;
    
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        self->_formatter = [[NSDateFormatter alloc]init];
        self->_formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssXXX";
    }
    return self;
}

+(void)createTable
{
    
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        //创建数据库表
        NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(sleepStart DOUBLE , sleepEnd DOUBLE NOT NULL, dateString TEXT, macAddress TEXT NOT NULL, hr FLOAT, hrv FLOAT, br FLOAT, spo2 FLOAT, hrDip FLOAT, duration DOUBLE, qulalityDuration DOUBLE, deepDuration DOUBLE, effieiency FLOAT, stagingData TEXT NOT NULL, restHR INT,  PRIMARY KEY (sleepEnd, macAddress))", TABLE_NM_SLEEP_DATA];
        
        bool succ = [db executeUpdate:sql];
        NSLog(@"create table %@ result =%d ", TABLE_NM_SLEEP_DATA, succ);
        
    }];
    
}


+(void)queryDbAvgSleepBy:(NSString *)macAddress
                   Begin:(NSDate *)beginDate
                     End:(NSDate *)endDate
                    Comp:(void(^)(DBSleepData * avgSleepData))cmpBlk
{
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        
        
        NSString *sql = [NSString stringWithFormat:@"SELECT COUNT(macAddress) as cntmacAddress, AVG(hr) as avgHr,  AVG(hrv) as avgHrv, AVG(br) as avgBr, AVG(spo2) as avgSpo2, AVG(hrDip) as avgHrDip,  AVG(duration) as avgDuration, AVG(qulalityDuration) as avgQulalityDuration, AVG(deepDuration) as avgDeepDuration, AVG(effieiency) as avgEffieiency  FROM %@ WHERE macAddress = ? AND sleepEnd BETWEEN ? AND ? ", TABLE_NM_SLEEP_DATA]; // 按睡眠时长倒序
        FMResultSet *rs = [db executeQuery:sql, macAddress, beginDate, endDate];
        DBSleepData *sleep = nil;
        while ([rs next]) {
            int cntmacAddress = [rs intForColumn:@"cntmacAddress"];
            if (cntmacAddress == 0) {
                continue;
            }
            
            sleep = [[DBSleepData alloc]init];
            
            sleep.hr = @([rs doubleForColumn:@"avgHr"]);
            sleep.hrv = @([rs doubleForColumn:@"avgHrv"]);
            sleep.br = @([rs doubleForColumn:@"avgBr"]);
            
            double tmpSpo = [rs doubleForColumn:@"avgSpo2"];
            sleep.spo2 = tmpSpo > 50 ? @(tmpSpo) : nil;
            
            sleep.hrDip = @([rs doubleForColumn:@"avgHrDip"]);
            sleep.duration = @([rs doubleForColumn:@"avgDuration"]);
            sleep.qulalityDuration = @([rs doubleForColumn:@"avgQulalityDuration"]);
            sleep.deepDuration = @([rs doubleForColumn:@"avgDeepDuration"]);
            sleep.effieiency = @([rs doubleForColumn:@"avgEffieiency"]);
            
           
            
        }
        [rs close];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (cmpBlk) {
                cmpBlk(sleep);
            }
        });
        
        return;
        
    }];
    
    
}





+(void)queryDbSleepOrderBySleepEndBy:(NSString *)macAddress Begin:(NSTimeInterval)beginTime EndTime:(NSTimeInterval)endTime Comp:(void(^)(NSMutableArray<DBSleepData *> *results))cmpBlk
{
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        
        NSString *sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE macAddress = ? AND sleepEnd BETWEEN ? AND ? ORDER BY sleepEnd ASC", TABLE_NM_SLEEP_DATA]; // 按睡眠时长倒序
        FMResultSet *rs = [db executeQuery:sql, macAddress, @(beginTime), @(endTime)];
        NSMutableArray<DBSleepData *> *results = [NSMutableArray new];
        while ([rs next]) {
           
            DBSleepData *sleep = [[DBSleepData alloc]init];
            sleep.sleepStart = @([rs doubleForColumn:@"sleepStart"]);
            sleep.sleepEnd = @([rs doubleForColumn:@"sleepEnd"]);
            sleep.dateString = [rs stringForColumn:@"dateString"];
            sleep.macAddress = [rs stringForColumn:@"macAddress"];
            sleep.hr = @([rs doubleForColumn:@"hr"]);
            sleep.hrv = @([rs doubleForColumn:@"hrv"]);
            sleep.br = @([rs doubleForColumn:@"br"]);
            int resthr = [rs intForColumn:@"restHR"];
            sleep.restHR = resthr > 0 ? @(resthr) :  nil;
            double spo = [rs doubleForColumn:@"spo2"];
            if (spo < 70) {
                spo = 98;
            }
            sleep.spo2 = @(spo);
            

            
            sleep.hrDip = @([rs doubleForColumn:@"hrDip"]);
            sleep.duration = @([rs doubleForColumn:@"duration"]);
            sleep.qulalityDuration = @([rs doubleForColumn:@"qulalityDuration"]);
            sleep.deepDuration = @([rs doubleForColumn:@"deepDuration"]);
            sleep.effieiency = @([rs doubleForColumn:@"effieiency"]);
            NSString *stagString = [rs stringForColumn:@"stagingData"];
            
            sleep.stagingData = [StagingDataV2 mj_objectWithKeyValues:stagString];
            
            [results addObject:sleep];

        }
        [rs close];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (cmpBlk) {
                cmpBlk(results);
            }
        });
        
        return;
        
    }];
}


+(void)queryDbSleepBy:(NSString *)macAddress Begin:(NSTimeInterval)beginTime EndTime:(NSTimeInterval)endTime Comp:(void(^)(NSMutableArray<DBSleepData *> *results))cmpBlk
{
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        
        NSString *sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE macAddress = ? AND sleepEnd BETWEEN ? AND ? ORDER BY sleepEnd ASC", TABLE_NM_SLEEP_DATA]; // 按睡眠时长倒序
        FMResultSet *rs = [db executeQuery:sql, macAddress, @(beginTime), @(endTime)];
        NSMutableArray<DBSleepData *> *results = [NSMutableArray new];
        while ([rs next]) {
           
            DBSleepData *sleep = [[DBSleepData alloc]init];
            sleep.sleepStart = @([rs doubleForColumn:@"sleepStart"]);
            sleep.sleepEnd = @([rs doubleForColumn:@"sleepEnd"]);
            sleep.dateString = [rs stringForColumn:@"dateString"];
            sleep.macAddress = [rs stringForColumn:@"macAddress"];
            sleep.hr = @([rs doubleForColumn:@"hr"]);
            sleep.hrv = @([rs doubleForColumn:@"hrv"]);
            sleep.br = @([rs doubleForColumn:@"br"]);
            int resthr = [rs intForColumn:@"restHR"];
            sleep.restHR = resthr > 0 ? @(resthr) :  nil;
            
            sleep.spo2 = @([rs doubleForColumn:@"spo2"]);
            

            
            sleep.hrDip = @([rs doubleForColumn:@"hrDip"]);
            sleep.duration = @([rs doubleForColumn:@"duration"]);
            sleep.qulalityDuration = @([rs doubleForColumn:@"qulalityDuration"]);
            sleep.deepDuration = @([rs doubleForColumn:@"deepDuration"]);
            sleep.effieiency = @([rs doubleForColumn:@"effieiency"]);
            NSString *stagString = [rs stringForColumn:@"stagingData"];
            
            
            if (sleep.duration.doubleValue <= 60 * 60 && sleep.duration.doubleValue > 0) {
                // 20 分钟到 60 分钟为nap
                sleep.isNap = YES;
            }
            
            sleep.stagingData = [StagingDataV2 mj_objectWithKeyValues:stagString];
            
            [results addObject:sleep];

        }
        [rs close];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (cmpBlk) {
                cmpBlk(results);
            }
        });
        
        return;
        
    }];
}


-(void)insert:(void(^)(BOOL succ))complete
{
    
    DB_WEAK_SELF
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        DB_STRONG_SELF
//        [db beginTransaction];
        
        // 检查是否重复
        int cnt = 0;
        NSString *sql =  [NSString stringWithFormat:@"SELECT COUNT(*) as cnt FROM %@ WHERE macAddress = ? AND sleepEnd BETWEEN ? AND ? ", TABLE_NM_SLEEP_DATA];
        FMResultSet *rs = [db executeQuery:sql, self.macAddress, self.sleepStart, self.sleepEnd];
        while ([rs next]) {
            cnt = [rs intForColumn:@"cnt"];

        }
        [rs close];
        if (cnt > 0) { // 已存在重复
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete) {
                    complete(NO);
                }
            });
            return;
        }
        
        NSString *sqlString = [NSString stringWithFormat:  @"INSERT INTO %@ (sleepStart , sleepEnd , dateString, macAddress , hr , hrv , br , spo2 , hrDip , duration , qulalityDuration , deepDuration , effieiency , stagingData, restHR) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", TABLE_NM_SLEEP_DATA];
        
        BOOL succ = [db executeUpdate:sqlString,
                     strongSelf.sleepStart , strongSelf.sleepEnd , strongSelf.dateString,
                     strongSelf.macAddress , strongSelf.hr ,strongSelf.hrv , strongSelf.br ,
                     strongSelf.spo2 , strongSelf.hrDip , strongSelf.duration ,
                     strongSelf.qulalityDuration , strongSelf.deepDuration , strongSelf.effieiency , [strongSelf.stagingData mj_JSONString], strongSelf.restHR
                    ];
        
//        [db commit];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (complete) {
                complete(succ);
            }
        });
        
    }];
}




+(void)dropTable {
#if DEBUG
 
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        //创建数据库表
        NSString   * sql = [NSString stringWithFormat:@"DROP TABLE %@", TABLE_NM_SLEEP_DATA];
        
        bool succ = [db executeUpdate:sql];
        NSLog(@"drop table %@ result =%d ", TABLE_NM_SLEEP_DATA, succ);
        
    }];
    
#endif
    
}


/// 查询最后一次睡眠的缓存,仅用于睡眠计算前的查询, 会删除最后一条记录
/// - Parameters:
///   - macAddress: 账号
///   - complete: 回调
+(void)queryFirstAndLastTimeOnlyForSleepCalc:(NSString *)macAddress Cmp:(void(^)(NSNumber * lastEndtime, NSNumber * firsttime, NSNumber *firstDataTime))complete
{
    
    
//    DB_WEAK_SELF
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        // 删除最后一条记录
        NSString *delSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE (sleepEnd in (SELECT MAX(sleepEnd) FROM %@  WHERE macAddress = ? ))", TABLE_NM_SLEEP_DATA, TABLE_NM_SLEEP_DATA];
        BOOL delSucc = [db executeUpdate:delSql, macAddress];

        NSNumber *lastEndtime = nil;
        NSNumber *firstTime = nil;

        NSString *sql =  [NSString stringWithFormat:@"SELECT MAX(sleepEnd) as lastEndTime, MIN(sleepEnd) as firstTime FROM %@ WHERE macAddress = ? ", TABLE_NM_SLEEP_DATA];
        FMResultSet *rs = [db executeQuery:sql, macAddress];
        while ([rs next]) {
            double lastEnd = [rs doubleForColumn:@"lastEndTime"];
            double first = [rs doubleForColumn:@"firstTime"];
            if (lastEnd > 100) {
                lastEndtime = @(lastEnd);
            }
            if (first > 100) {
                firstTime = @(first);
            }
            
        }
        [rs close];
        
        NSNumber *firstDataTime = [DBHistoryDataSr03 querySyncminTimeBymacAdres:macAddress Db:db];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (complete) {
                complete(lastEndtime, firstTime, firstDataTime);
            }
        });
        
    }];
}


/// 查询最后一次睡眠的缓存
/// - Parameters:
///   - macAddress: 账号
///   - complete: 回调
+(void)queryFirstAndLastTime:(NSString *)macAddress Cmp:(void(^)(NSNumber * lastEndtime, NSNumber * firsttime, NSNumber *firstDataTime))complete
{
    
    
//    DB_WEAK_SELF
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
//        DB_STRONG_SELF
        NSNumber *lastEndtime = nil;
        NSNumber *firstTime = nil;

        NSString *sql =  [NSString stringWithFormat:@"SELECT MAX(sleepEnd) as lastEndTime, MIN(sleepEnd) as firstTime FROM %@ WHERE macAddress = ? ", TABLE_NM_SLEEP_DATA];
        FMResultSet *rs = [db executeQuery:sql, macAddress];
        while ([rs next]) {
            double lastEnd = [rs doubleForColumn:@"lastEndTime"];
            double first = [rs doubleForColumn:@"firstTime"];
            if (lastEnd > 100) {
                lastEndtime = @(lastEnd);
            }
            if (first > 100) {
                firstTime = @(first);
            }
            
        }
        [rs close];
        
        NSNumber *firstDataTime = [DBHistoryDataSr03 querySyncminTimeBymacAdres:macAddress Db:db];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (complete) {
                complete(lastEndtime, firstTime, firstDataTime);
            }
        });
        
    }];
}





/// 其他的计算并保存
/// - Parameters:
///   - restHr: 静息心率
///   - complete: 完成回调
-(void)doOtherCalcAndSaveComplete:(void(^)(BOOL succ))complete
{
    
    self.sleepStart = @(self.stagingData.startTime);
    self.sleepEnd = @(self.stagingData.endTime);
    self.hr = @(self.stagingData.averageHr);
    self.dateString = [_formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:self.stagingData.endTime]];
    
    // 前一天的时间范围
    NSDate *restHrDateBegin = [TimeUtils zeroOfBeforeDayDate:[NSDate dateWithTimeIntervalSince1970:self.sleepEnd.doubleValue]];
    NSDate *restHrDateEnd = [TimeUtils zeroOfDate:[NSDate dateWithTimeIntervalSince1970:self.sleepEnd.doubleValue]];
    
    DB_WEAK_SELF
    [DBHistoryDataSr03 queryueryRestHrBymacAdres:self.macAddress Date:restHrDateBegin  CMP:^(NSNumber * _Nonnull restHr) {
        DB_STRONG_SELF
        strongSelf.restHR = restHr; // 前一天的静息
        
        // 1 睡眠时长
        strongSelf.duration = [ContributionScoreObj calcSleepDuration:strongSelf.stagingData];
        // 2 质量睡眠时长
        strongSelf.qulalityDuration = [ContributionScoreObj calcQualitySleepDuration:strongSelf.stagingData];
        // 3 深度睡眠时长
        strongSelf.deepDuration = [ContributionScoreObj calcDeepSleepDuration:strongSelf.stagingData];
        // 4. 睡眠效率
        strongSelf.effieiency = [ContributionScoreObj calcSleepEffecy:strongSelf.stagingData];
        // 5 呼吸率
        strongSelf.br = @(strongSelf.stagingData.averageHr / 4);
        // 6 沉浸率
        [strongSelf calcDipPercentInSleepWithRestHr:restHr];
//        DebugNSLog(@"lzp 开始睡眠相关查询");
        // 7 血氧
        
        [strongSelf calcAvgSpo2InSleepWithCmp:^{
//            STRONG_SELF_NOT_CHECK
//            DebugNSLog(@"lzp 血氧完毕 self = %@", strongSelf);
            // 8 平均hrv
            [strongSelf calcAvgHrvInSleepWithMac:strongSelf.macAddress Cmp:^{
    //            STRONG_SELF
//                DebugNSLog(@"lzp hrv完毕 ");
                // 保存到db
                [strongSelf insert:^(BOOL succ) {
                    if (complete) {
                        complete(succ);
                    }
//                    DebugNSLog(@"睡眠保存 %d", succ);
                    return;
                }];
//
//                [strongSelf calcThermemoterValusInSleepWithCmp:^{
//    //                STRONG_SELF
//                    DebugNSLog(@"lzp 体温完毕 ");
//
//                }];
                
            }];
        }];
        
        
    }];
    
   
    
}


-(void)appendSleep:(DBSleepData *)newSleepData
{
    
    
    self.duration = @((self.duration.doubleValue + newSleepData.duration.doubleValue));
    self.qulalityDuration = @(self.qulalityDuration.doubleValue + newSleepData.qulalityDuration.doubleValue);
    self.deepDuration = @(self.deepDuration.doubleValue + newSleepData.deepDuration.doubleValue);
    self.effieiency = @((self.effieiency.floatValue + newSleepData.effieiency.floatValue)/2.0 );
}

/// 计算心率沉浸率
/// - Parameters:
///   - hrInNotActive:
///   - complete:
-(void)calcDipPercentInSleepWithRestHr:(NSNumber *)hrInNotActive {
    
    double averageHrInSleep = self.stagingData.averageHr;
    float percent = 0;
    if (hrInNotActive.intValue != 0) {
        
        percent = (hrInNotActive.floatValue - averageHrInSleep) / hrInNotActive.floatValue;
        if (percent < 0) {
            percent = 0;
        }
    }
    
    
    self.hrDip = @(percent);
    
}

/// 睡眠期间的血氧平均
/// - Parameter complete: 完成
-(void)calcAvgSpo2InSleepWithCmp:(void(^)(void))complete {
    DB_WEAK_SELF
    [DBHistoryDataSr03 queryBy:self.macAddress Begin:[NSDate dateWithTimeIntervalSince1970:self.stagingData.startTime] End:[NSDate dateWithTimeIntervalSince1970:self.stagingData.endTime] OrderBeTimeDesc:NO Cpmplete:^(NSMutableArray<DBHistoryDataSr03 *> * _Nonnull results) {
        
        DB_STRONG_SELF
        float total = 0;
        for (int i = 0; i < results.count; i++) {
            total += results[i].bloodOxygen.floatValue;
        }
        if (results.count > 0) {
            total /= results.count; // 求平均
        }
        if (total > 92 && total <= 100) {
            strongSelf.spo2 = @(total);
        } else {
            strongSelf.spo2 = @([Tools getRandomNumber:96 to:99]);
        }
        
        if (complete) {
            complete();
        }
        
    }];
    

    
}



/// 睡眠期间的平均hrv
/// - Parameter complete: 回调
-(void)calcAvgHrvInSleepWithMac:(NSString * )macAddress Cmp:(void(^)(void))complete {
    DB_WEAK_SELF
//    [DBHrv queryAverage:self.macAddress Begin:[NSDate dateWithTimeIntervalSince1970:self.stagingData.startTime] End:[NSDate dateWithTimeIntervalSince1970:self.stagingData.endTime] Cpmplete:^(NSNumber * _Nullable average, NSNumber * _Nullable maxTime, NSNumber * _Nullable minTime) {
//        DB_STRONG_SELF
//        strongSelf.hrv = average;
//        if (complete) {
//            complete();
//        }
//
//    }];
    [DBHistoryDataSr03 queryBy:macAddress Begin:[NSDate dateWithTimeIntervalSince1970:self.stagingData.startTime]
                           End:[NSDate dateWithTimeIntervalSince1970:self.stagingData.endTime] OrderBeTimeDesc:NO Cpmplete:^(NSMutableArray<DBHistoryDataSr03 *> * _Nonnull results) {
        DB_STRONG_SELF
        if (results.count > 0) {
            __block float  average = 0;
            __block NSInteger usefulCount = 0;
            [results enumerateObjectsUsingBlock:^(DBHistoryDataSr03 * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.hrv.floatValue > 1) {
                    average += obj.hrv.floatValue;
                    usefulCount++;
                }
                
            }];
            average /= usefulCount;
            
            strongSelf.hrv = @(average);
        }
     
        
        if (complete) {
            complete();
        }
    }];
    
    
    
}


+(void)testDel:(NSString *)macAddress Endtime:(NSString *)timeString CMP:(void(^)(BOOL succ))complete
{
#if DEBUG
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        
//        [db beginTransaction];
        
        NSString *sql =  [NSString stringWithFormat:@"DELETE FROM %@ WHERE dateString = ? AND macAddress = ?", TABLE_NM_SLEEP_DATA];
        BOOL succ = [db executeUpdate:sql, timeString, macAddress];
        
//        [db commit];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (complete) {
                complete(succ);
            }
        });
       
    }];
    
#endif
}

+(void)clearColumnBy:(NSString *)macAddress DB:(FMDatabase * _Nonnull )db
{

    NSString *sql =  [NSString stringWithFormat:@"DELETE FROM %@ WHERE  macAddress = ?", TABLE_NM_SLEEP_DATA];
    BOOL succ = [db executeUpdate:sql, macAddress];
        

}


+(void)debuginsert:(NSMutableArray<NSDictionary *> *)dataArray MacAddress:(NSString *)macAddress CMP:(void(^)(BOOL succ))complete
{
    
    DB_WEAK_SELF
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        DB_STRONG_SELF
//        [db beginTransaction];
        
        BOOL allsucc = YES;
        // 检查是否重复
        for (NSDictionary *dict in dataArray) {
            
            NSString *sqlString = [NSString stringWithFormat:  @"INSERT OR REPLACE INTO %@ (sleepStart , sleepEnd , dateString, macAddress , hr , hrv , br , spo2 , hrDip , duration , qulalityDuration , deepDuration , effieiency , stagingData, restHR) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", TABLE_NM_SLEEP_DATA];
            
            BOOL succ = [db executeUpdate:sqlString,
                         dict[@"sleepStart"] ,
                         dict[@"sleepEnd"] ,
                         dict[@"dateString"],
                         macAddress ,
                         dict[@"hr"] ,
                         dict[@"hrv"] ,
                         dict[@"br"] ,
                         dict[@"spo2"] ,
                         dict[@"hrDip"] ,
                         dict[@"duration"] ,
                         dict[@"qulalityDuration"] ,
                         dict[@"deepDuration"] ,
                         dict[@"effieiency"] ,
                         dict[@"stagingData"],
                         dict[@"restHR"]
                        ];
            allsucc = allsucc && succ;
            
        }
        

        
//        [db commit];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (complete) {
                complete(allsucc);
            }
        });
        
    }];
}


@end
